<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item :label="$t('时间')">
              <a-date-picker
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.bTime"
              ></a-date-picker>
              <span class="query-group-split-cust"></span>
              <a-date-picker
                :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择结束时间')"
                class="query-group-cust"
                v-model="queryParam.eTime"
              ></a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="6" :md="7" :sm="24">
            <a-form-item :label="$t('操作员')">
              <a-select v-model="queryParam.createBy">
                <a-select-option :key="index" v-for="(item, index) in userList" :value="item.value">{{
                  item.text
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="8" :md="9" :sm="24">
            <a-form-item :label="$t('设备名称(编码)')">
              <a-select show-search :filter-option="false" @search="handleSearch" v-model="queryParam.deviceId">
                <a-select-option :value="item.id" :key="index" v-for="(item, index) in deviceList">
                  <span>{{ item.name }}</span>
                  <span v-if="item.name != $t('全部')">({{ item.id }})</span>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6" v-if="!tenantId">
            <a-form-item :label="$t('门店')" :labelCol="{ span: 4}" :wrapperCol="{ span: 19 }" style="margin-bottom:10px">
              <a-select v-model="queryParam.shopCode" style="width:100%">
                <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                  >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{$t('查询')}}</a-button>
              <a-dropdown>
                <a-menu slot="overlay" @click="handleDateClick">
                  <a-menu-item key="1"> {{$t('今日')}} </a-menu-item>
                  <a-menu-item key="2"> {{$t('近三天')}} </a-menu-item>
                  <a-menu-item key="3"> {{$t('近七天')}} </a-menu-item>
                  <a-menu-item key="4"> {{$t('近一月')}} </a-menu-item>
                  <a-menu-item key="5"> {{$t('近三月')}} </a-menu-item>
                  <a-menu-item key="6"> {{$t('近半年')}} </a-menu-item>
                  <a-menu-item key="7"> {{$t('本年')}} </a-menu-item>
                </a-menu>
                <a-button type="primary" style="margin-left: 8px"> {{ $t('快捷查询') }} <a-icon type="down" /></a-button>
              </a-dropdown>
              <a-button type="primary" @click="searchReset" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a-button
                type="primary" :loading="exloading"
                @click="handleExportXls($t('场地业务汇总'))"
                style="margin-left: 8px"
                v-has="'BusinessTypeTotalController:export'"
                >{{ $t('导出') }}</a-button
              >
              <a-button type="primary" v-print="'#printme'" style="margin-left: 8px" v-has="'BusinessTypeTotalController:print'">{{$t('打印')}}</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator"></div>

    <!-- table区域-begin -->
    <div id="printme">
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSources"
        :pagination="false"
        :loading="loading"
        class="j-table-force-nowrap"
        :customHeaderRow="customHeaderRow"
        :customRow="customRow"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            {{ $t('下载') }}
          </a-button>
        </template>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">{{ $t('编辑') }}</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">{{ $t('更多') }}<a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">{{ $t('详情') }}</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm :title="$t('确定删除吗?')" @confirm="() => handleDelete(record.id)">
                  <a>{{ $t('删除') }}</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
  </a-card>
</template>

<script>
import Vue from 'vue'
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { TENANT_ID } from '@/store/mutation-types'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '@/api/manage'
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'

export default {
  name: 'SiteBusinessSummary',
  mixins: [JeecgListMixin, mixinDevice],
  components: {},
  data() {
    return {
      description: '场地业务汇总页面',
      moment,
      // 表头
      columns: [
        {
          title: this.$t('业务类型'),
          align: 'center',
          dataIndex: 'typeId_dictText',
        },
        {
          title: this.$t('业务笔数'),
          align: 'center',
          dataIndex: 'count',
          customCell: function (col) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            return text.toFixed(0);
          }
        },
        {
          title: this.$t('金额'),
          align: 'center',
          dataIndex: 'cash',
          customCell: function (col) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            return (text ==null || text =="" || text ==undefined)?0.00.toFixed(2):parseFloat(text).toFixed(2);
          }
        },
        {
          title: this.$t('限时币'),
          align: 'center',
          dataIndex: 'limitCoin',
          customCell: function (col) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            return (text ==null || text =="" || text ==undefined)?0.00.toFixed(0):parseFloat(text).toFixed(0);
          }
        },
        {
          title: this.$t('实币'),
          align: 'center',
          dataIndex: 'phyCoin',
          customCell: function (col) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            return (text ==null || text =="" || text ==undefined)?0.00.toFixed(0):parseFloat(text).toFixed(0);
          }
        },
      ],
      url: {
        list: '/report/day/businessTypeTotal/list',
        delete: '',
        deleteBatch: '',
        exportXlsUrl: '/report/day/businessTypeTotal/exportXls',
        importExcelUrl: '',
      },
      isNoPageTotal: true,
      deviceList: [],
      userList: [],
      queryParam: {
        bTime: moment().format('YYYY-MM-DD 00:00:00'),
        eTime: moment().format('YYYY-MM-DD 23:59:59'),
        createBy: '',
        deviceId: '',
        shopCode: ''
      },
      dataSources: [],
      tenantId: Vue.ls.get(TENANT_ID) ? Vue.ls.get(TENANT_ID) : 0,
      shops: []
    }
  },
  created() {
    if(!this.tenantId){
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: 0, title: this.$t('总部') })
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
      this.queryParam.shopCode = ''
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  watch: {
    dataSource(val) {
      if (val.length > 0) {
        let total = {
          alottery: 0,
          cash: 0,
          coin: 0,
          count: 0,
          integral: 0,
          lottery: 0,
          points: 0,
          limitCoin: 0,
          phyCoin: 0,
          typeId_dictText: '合计',
        }
        val.forEach((v) => {
          total.alottery+=v.alottery
          total.cash+=v.cash
          total.coin+=v.coin
          total.count+=v.count
          total.integral+=v.integral
          total.lottery+=v.lottery
          total.points+=v.points
          total.limitCoin+=v.limitCoin
          total.phyCoin+=v.phyCoin
        })
        total.cash=total.cash.toFixed(2)
        total.coin=total.coin.toFixed(2)
        total.points=total.points.toFixed(2)
        total.limitCoin=total.limitCoin.toFixed(0)
        val=val.concat([total])
        this.dataSources=val
      }else{
        this.dataSources=[]
      }
    },
  },
  methods: {
    initDictConfig() {
      if (localStorage.getItem('operateCoin') == 1) {
        this.columns.splice(this.columns.length - 1, 0, {
          title: this.$t('代币'),
          align: 'center',
          dataIndex: 'coin',
          customCell: function (col) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = (text ==null || text =="" || text ==undefined)?0:parseFloat(text);
            return text.toFixed(2);
          }
        })
      }
      if (localStorage.getItem('operateLottery') == 1) {
        this.columns.splice(this.columns.length - 1, 0, {
          title: this.$t('彩票'),
          align: 'center',
          dataIndex: 'lottery',
          customCell: function (col) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = (text ==null || text =="" || text ==undefined)?0:parseFloat(text);
            return text.toFixed(0);
          }
        })
      }
      if (localStorage.getItem('operateCredit') == 1) {
        this.columns.splice(this.columns.length - 1, 0, {
          title: this.$t('积分'),
          align: 'center',
          dataIndex: 'integral',
          customCell: function (col) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = (text ==null || text =="" || text ==undefined)?0:parseFloat(text);
            return text.toFixed(0);
          }
        })
      }
      if (localStorage.getItem('operateALottery') == 1) {
        this.columns.splice(this.columns.length - 1, 0, {
          title: this.$t('A票'),
          align: 'center',
          dataIndex: 'alottery',
          customCell: function (col) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = (text ==null || text =="" || text ==undefined)?0:parseFloat(text);
            return text.toFixed(0);
          }
        })
      }
      if (localStorage.getItem('operateACoin') == 1) {
        this.columns.splice(this.columns.length - 1, 0, {
          title: this.$t('A币'),
          align: 'center',
          dataIndex: 'points',
          customCell: function (col) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = (text ==null || text =="" || text ==undefined)?0:parseFloat(text);
            return text.toFixed(0);
          }
        })
      }
      initDictOptions('sys_user,realname,realname').then((res) => {
        this.userList = res.result
        this.userList.unshift({ value: '', text: this.$t('全部') })
      })
      this.handleSearch('')
    },
    handleSearch(value) {
      let query = {}
      if (value) {
        query.deviceInfo = value
      }
      getAction('/device/bisDeviceInfo/list', query).then((res) => {
        if (res.success) {
          this.deviceList = res.result.records
          this.deviceList.unshift({ id: '', name: this.$t('全部') })
        }
      })
    },
    searchReset() {
      this.handleSearch('')
      this.queryParam = {
        bTime: moment().format('YYYY-MM-DD 00:00:00'),
        eTime: moment().format('YYYY-MM-DD 23:59:59'),
        createBy: '',
        deviceId: ''
      }
      if(!this.tenantId){
        this.queryParam.shopCode = ''
      }
      this.searchQuery()
    },
    customRow(r, i) {
      return {
        on: {
          click: () => {
            let x = this.selectedRowIndex.findIndex(r=>{return r=='a'+this.ipagination.current+''+i})
            if( x == -1 ){
              this.selectedRowIndex.push('a'+this.ipagination.current+''+i)
            }else{
              this.selectedRowIndex.splice(x, 1)
            }
          }
        },
        style: {
          whiteSpace: 'break-spaces',
          wordBreak: 'break-word',
          overflowWrap: 'break-word',
          backgroundColor: this.selectedRowIndex.findIndex(r=>{return r=='a'+this.ipagination.current+''+i}) > -1 ? '#FFECE6' : '',
          fontWeight: r.typeId_dictText == '合计' ? 700 : 400,
        },
      }
    },
    handleDateClick(evt){
      if(evt.key=='1'){
        this.queryParam.bTime=moment().format('YYYY-MM-DD 00:00:00')
        this.queryParam.eTime=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='2'){
        this.queryParam.bTime=moment().subtract(2,'day').format('YYYY-MM-DD 00:00:00')
        this.queryParam.eTime=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='3'){
        this.queryParam.bTime=moment().subtract(6,'day').format('YYYY-MM-DD 00:00:00')
        this.queryParam.eTime=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='4'){
        this.queryParam.bTime=moment().subtract(1, 'month').format('YYYY-MM-DD 00:00:00')
        this.queryParam.eTime=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='5'){
        this.queryParam.bTime=moment().subtract(3,'month').format('YYYY-MM-DD 00:00:00')
        this.queryParam.eTime=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='6'){
        this.queryParam.bTime=moment().subtract(6,'month').format('YYYY-MM-DD 00:00:00')
        this.queryParam.eTime=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='7'){
        this.queryParam.bTime=moment().startOf('year').format('YYYY-MM-DD 00:00:00')
        this.queryParam.eTime=moment().format('YYYY-MM-DD 23:59:59')
      }
      this.searchQuery()
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>